package com.atguigu.IO;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    public static void main(String[] args) throws IOException {
        TcpEchoServer server=new TcpEchoServer(9090);
        server.start();
    }
    private ServerSocket serverSocket=null;
   public TcpEchoServer(int port) throws IOException {
       serverSocket=new ServerSocket(port);
   }
   public void start() throws IOException {
       System.out.println("服务器启动");
       ExecutorService service=Executors.newCachedThreadPool();
       while(true){
           //1. 先调用accept接收来自客户端的连接
           Socket socket = serverSocket.accept();
//           Thread t=new Thread(()->{
//               try {
//                   processClient(socket);
//               } catch (IOException e) {
//                   e.printStackTrace();
//               }
//           });
//           //2.处理连接
//           t.start();
           service.submit(new Runnable() {
               @Override
               public void run() {
                   try {
                       processClient(socket);
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
               }
           });
       }
   }

    private void processClient(Socket socket) throws IOException {
        System.out.printf("[%s: %d] 客户端上线",socket.getInetAddress().toString(),socket.getPort());
        //接下来处理客户端的请求
        try(InputStream inputStream= socket.getInputStream();
                OutputStream outputStream=socket.getOutputStream()) {
            while(true){
                //1.读取请求并解析
                Scanner scanner=new Scanner(System.in);
                if(!scanner.hasNext()){
                    //连接断开
                    System.out.println("客户端下线"+socket.getInetAddress().toString()+socket.getPort());
                    break;
                }
                String request=scanner.next();
                //2.根据请求计算相应
                String response=process(request);
                //3.把响应写回客户端
                PrintWriter printWriter=new PrintWriter(outputStream);
                printWriter.println(response);
                //刷新缓冲区
                printWriter.flush();
                System.out.printf("[%s %d] req:%s resp: %s\n",socket.getInetAddress().toString(),socket.getPort(),
                            request,response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            socket.close();

        }
    }

    public String process(String request) {
       return request;
    }
}
